package com.ikingtech.platform.service.push.dingtalk.service.impl;

import com.fasterxml.jackson.core.type.TypeReference;
import com.ikingtech.framework.sdk.context.exception.FrameworkException;
import com.ikingtech.framework.sdk.utils.Tools;
import com.ikingtech.platform.service.push.dingtalk.dto.ButtonDTO;
import com.ikingtech.platform.service.push.dingtalk.dto.DingTalkSendMessageDTO;
import com.ikingtech.platform.service.push.dingtalk.dto.SonarProjectMetricDTO;
import com.ikingtech.platform.service.push.dingtalk.dto.SonarWebhookMessageDTO;
import com.ikingtech.platform.service.push.dingtalk.service.RobotInterface;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * created on 2023-05-25 16:57
 *
 * @author wub
 */

@Slf4j
@Service
public class SonarMessageService implements RobotInterface {

    @Override
    public DingTalkSendMessageDTO analysis(String payLoad) throws FrameworkException {

        SonarWebhookMessageDTO sonarMessage = Tools.Json.toBean(payLoad, new TypeReference<>() {
        });
        if (sonarMessage == null || Tools.Str.isBlank(sonarMessage.getServerUrl())) {
            log.error("payLoad参数错误或serverUrl为空,请检查 payLoad:{}", payLoad);
            throw new FrameworkException("payLoad参数错误或serverUrl为空");
        }
        String projectMetricStr = Tools.Http.get(sonarMessage.getServerUrl() + "/api/measures/component?component=" + sonarMessage.getProject().getKey() + "&metricKeys=bugs%2Ccode_smells%2Cvulnerabilities",
                "Bearer squ_7148ba270966d5ebbd8ae4663da4c8d8f0925031");
        SonarProjectMetricDTO projectMetric = Tools.Json.toBean(projectMetricStr, new TypeReference<>() {
        });
        String bugCount = "0";
        String codeSmellCount = "0";
        String vulnerabilities = "0";
        if (null != projectMetric) {
            for (SonarProjectMetricDTO.ComponentDTO.MeasuresDTO measure : projectMetric.getComponent().getMeasures()) {
                if ("bugs".equals(measure.getMetric())) {
                    bugCount = measure.getValue();
                }
                if ("code_smells".equals(measure.getMetric())) {
                    codeSmellCount = measure.getValue();
                }
                if ("vulnerabilities".equals(measure.getMetric())) {
                    vulnerabilities = measure.getValue();
                }
            }
        }
        String title = "SonarQube 代码静态检测";
        String content = "<font face=\"黑体\" color=\"#4B9FD5\">**SonarQube 代码静态检测**</font>" +
                "\n\n> 项目名称\n\n " + "**" + sonarMessage.getProject().getName() + "**" +
                "\n\n> 分支\n\n" + "**" + sonarMessage.getBranch().getName() + "**" +
                "\n\n> 检测时间\n\n" + "**" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")) + "**" +
                "\n\n> 摘要信息\n\n" + "* **缺陷：" + bugCount + "个**\n\n" + "* **漏洞：" + vulnerabilities + "个**\n\n" + "* **代码异味：" + codeSmellCount + "个**\n\n";
        ButtonDTO buttonDTO = new ButtonDTO();
        buttonDTO.setTitle("查看结果");
        buttonDTO.setUrl("dingtalk://dingtalkclient/page/link?url=" + URLEncoder.encode(sonarMessage.getProject().getUrl(), StandardCharsets.UTF_8) + "&pc_slide=false");

        String webhook = "https://oapi.dingtalk.com/robot/send?access_token=96b7357b3b34ec54b6a695a2319c618f8659fb32a9710008b8ba2b5f1625287a";
        return new DingTalkSendMessageDTO(webhook, title, content, null, Tools.Coll.newList(buttonDTO));
    }

    @Override
    public String getType() {
        return "SONAR";
    }
}
